package one.bugu.android.demon.util;

import android.graphics.PointF;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: LangK
 * Created Date 2018/9/19
 * Time: 16:59
 * Description:
 */
public class RandomLocationUtil {

    /**
     * 位置列表
     */
    private Map<Integer, PointF> listPoint = new HashMap<>();

    /**
     * 随机数列表
     */
    private Map<Integer, PointF> listRatio = new HashMap<>();

    /**
     * 左x...左y...右x...右y...每个点占用半径大小
     */
    private float x, y, f_x, f_y, radius;
    /**
     * 最大数量
     */
    private int maxNum = 10;


    private float[] xList = {0.0f, 0.25f, 0.5f, 0.75f, 1.0f};
    private float[] yList = {0.0f, 0.3f};

    /**
     * 构造函数，声明随机生成位置的区域
     *
     * @param x      左x...
     * @param y      左y...
     * @param f_x    右x...
     * @param f_y    右y...
     * @param radius 每个点占用半径大小
     */
    public RandomLocationUtil(float x, float y, float f_x, float f_y, float radius) {
        this.x = x;
        this.y = y;
        this.f_y = f_y;
        this.f_x = f_x;
        this.radius = radius;
    }

    /**
     * 生成新位置
     *
     * @return
     */
    public PointF generationNewPoint(int index) {
        if (listPoint.size() >= maxNum) {
            return null;
        }
        PointF x_r;
        if (index == -1) {
            x_r = new PointF(0.5f, 0.3f);
        } else {
            x_r = generationUseable(index);
        }
        listRatio.put(index, x_r);
        float result_x = x_r.x * (f_x - x) + x;
        float result_y = x_r.y * (f_y - y) + y;
        PointF result = new PointF(result_x, result_y);
        listPoint.put(index, result);
        return result;
    }

    private static final float MIN_RATIO = 0.1F;

    /**
     * 生成可用的随机数
     *
     * @return
     */
    private PointF generationUseable(int index) {
        int ratio_x = (int) (Math.random() * xList.length);
        int ratio_y = (int) (Math.random() * yList.length);
        for (PointF point : listRatio.values()) {
            if (Math.abs(point.x - xList[ratio_x]) < 0.07) {
                if (Math.abs(point.y - yList[ratio_y]) < 0.07) {
                    return generationUseable(index);
                }
            }
        }
        if (index % 2 == 0) {
            return new PointF((xList[ratio_x] + 0.06f), (yList[ratio_y] + 0.06f));
        } else {
            return new PointF(xList[ratio_x], yList[ratio_y]);
        }
    }

    public void remove(int tag) {
        try {
            listPoint.remove(tag);
            listRatio.remove(tag);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean isEmpty() {
        return listPoint.isEmpty();
    }
}
